package services

import (
	"git.hortorgames.com/orange/tang/log"
	"git.hortorgames.com/serverless/htgserver/apiserver"
	"git.hortorgames.com/serverless/htgserver/apiserver/data"
	"sync"
	"time"
)

type game struct {
	gamesCache *sync.Map
}

type gameCache struct {
	Game    *data.TDGame
	Timeout time.Time
}

var Game = &game{
	gamesCache: &sync.Map{},
}

func (g *game) FindGame(apiClient *apiserver.InternalApiClient, gameId string) (game *data.TDGame) {
	if v, ok := g.gamesCache.Load(gameId); ok && time.Now().Before(v.(*gameCache).Timeout) {
		return v.(*gameCache).Game
	}

	type ReqGameGet struct {
		GameId string `json:"gameId,omitempty"`
	}
	resp := apiClient.Call("/game/get", &ReqGameGet{GameId: gameId}, &game)
	if resp.Code != 0 {
		log.Error("FindGame error", "err", resp.Error)
		return nil
	}
	if game != nil {
		g.gamesCache.Store(gameId, &gameCache{Game: game, Timeout: time.Now().Add(time.Minute * 10)})
	}
	return game
}
